package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.TimeZoneUtil;
import util.enviaEmail;
import bean.OSBean;
import bean.secretarioBean;
import conexao.Conexao;
import dao.OSDao;
import dao.secretarioDao;

public class cadastrarOsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public cadastrarOsServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		if (request.getParameter("novaOsSelCliente") == "") {
			out.println("Por favor selecione um cliente.");
			return;
		}else if (request.getParameter("novaOsValor") == "") {
			out.println("Informe o valor da OS.");
			return;
		}else if (request.getParameter("novaOsTextarea") == "") {
			out.println("A descrição não pode ser vazio.");
			return;
		}else{
		
		Integer idCliente = Integer.parseInt(request.getParameter("novaOsSelCliente"));	
		String descricao = request.getParameter("novaOsTextarea");	
		Double valor = Double.parseDouble(request.getParameter("novaOsValor"));	
		Integer idSecretario = Integer.parseInt(request.getParameter("novaOsIdFuncionario"));
		String urgen = request.getParameter("urgente");
		int urgente = 0;
		if(urgen != null){
			urgente = 1;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		SimpleDateFormat sdfBra = new SimpleDateFormat("dd/MM/yyyy");
		long prazoEntrega = 0;
		Timestamp dataEntrada = null;
		try {
			if(request.getParameter("novaOsPrazoHora") != "" && request.getParameter("novaOsPrazoDia") != ""){
				prazoEntrega = sdf.parse(request.getParameter("novaOsPrazoDia")+" "+request.getParameter("novaOsPrazoHora")+":00").getTime();
			}else if(request.getParameter("novaOsPrazoHora") == "" && request.getParameter("novaOsPrazoDia") != ""){
				prazoEntrega = sdf.parse(request.getParameter("novaOsPrazoDia")+" 00:00:00").getTime();
			}else if(request.getParameter("novaOsPrazoHora") != "" && request.getParameter("novaOsPrazoDia") == ""){
				prazoEntrega = sdf.parse(sdfBra.format(new Date())+" "+request.getParameter("novaOsPrazoHora")+":00").getTime();
			}else if(request.getParameter("novaOsPrazoHora") == "" && request.getParameter("novaOsPrazoDia") == ""){
				
			}
			dataEntrada = new TimeZoneUtil().getHoraLocal();
			} catch (ParseException e1) {
			out.println("Data ou Hora inválida.");
			return;
		} 
		
		String situacao = "novaOS";
			
			OSBean OS = new OSBean();
			OS.setIdCliente(idCliente);
			OS.setIdEmpresa((Integer)request.getSession().getAttribute("idempresa"));
			OS.setDescricao(descricao);
			OS.setValor(valor);
			OS.setUrgente(urgente);
			OS.setSituacao(situacao);
			OS.setDataEntrada(dataEntrada);
			if(prazoEntrega != 0){
				OS.setPrazoEntrega(new Timestamp(prazoEntrega));
			}		
			
			secretarioBean secBean = new secretarioBean();
			secBean.setIdsecretario(idSecretario);
		
			try {
				
				new OSDao().inserir(conn, OS);
				new secretarioDao().inserir(conn, secBean);
				conn.commit();
				
			} catch (Exception e) {
				try {
					conn.rollback();
				} catch (Exception ex) {
					new enviaEmail().enviar(ex);
					ex.printStackTrace();
				}
				new enviaEmail().enviar(e);
				throw new RuntimeException(e);
			} finally {
				try {
					conn.close();
				} catch (Exception ex) {
					new enviaEmail().enviar(ex);
				}
			}
		}
		
	}

}
